package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    // 查询用户信息
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }

        // 获取用户id
        Integer userId = user.getId();
        // 通过用户id获取用户的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        // 遍历用户集合获取权限
        for (Role role : roles) {
            // 获取用户id
            Integer roleId = role.getId();
            // 通过用户id获取权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            // 给角色绑定权限
            role.setPermissions(permissions);
        }
        // 给用户添加角色
        user.setRoles(roles);
        return user;
    }
}
